package com.dg11185.nearshop.activity.home;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;

import android.content.Intent;
import android.graphics.Typeface;
import android.graphics.drawable.AnimationDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.SparseArray;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.GridView;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RadioGroup;
import android.widget.ScrollView;
import android.widget.SimpleAdapter;
import android.widget.TextView;

import com.android.nearshop.R;
import com.dg11185.libs.network.NetClient;
import com.dg11185.libs.network.http.client.HttpRequest.ActionListener;
import com.dg11185.libs.utils.netstate.NetWorkUtils;
import com.dg11185.libs.utils.print.PrintUtils;
import com.dg11185.nearshop.activity.BaseFragment;
import com.dg11185.nearshop.activity.home.actys.NewActysHelper;
import com.dg11185.nearshop.activity.home.actys.TabloidActivity;
import com.dg11185.nearshop.activity.shop.ShopDetailActivity;
import com.dg11185.nearshop.activity.shop.ShopListActivity;
import com.dg11185.nearshop.activity.welcome.MainTabActivity;
import com.dg11185.nearshop.app.Constants;
import com.dg11185.nearshop.app.StaticData;
import com.dg11185.nearshop.net.CacheConstant;
import com.dg11185.nearshop.net.NetCacheClient;
import com.dg11185.nearshop.net.entity.Area;
import com.dg11185.nearshop.net.request.GetAreaListRequest;
import com.dg11185.nearshop.net.request.GetBrandListRequest;
import com.dg11185.nearshop.net.request.GetDayMerListRequest;
import com.dg11185.nearshop.net.response.GetAreaListResponse;
import com.dg11185.nearshop.net.response.GetBrandListResponse;
import com.dg11185.nearshop.net.response.GetDayMerListResponse;
import com.dg11185.nearshop.view.adapter.F_ShopListAdapter;
import com.dg11185.nearshop.view.adapter.V_ShopListAdapter;
import com.handmark.pulltorefresh.library.ILoadingLayout;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.Mode;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshScrollView;
import com.umeng.analytics.MobclickAgent;
import com.wlper.lib.sys.Screen;
import com.wlper.lib.uitls.LogUtils;
import com.wlper.lib.uitls.TimeUtils;
import com.wlper.lib.uitls.ViewUtils;
import com.wlper.lib.view.ExpandableTab;
import com.wlper.lib.view.HorizontalExpandableList;
import com.wlper.lib.view.adapter.SimpleAdapterWithMarker;
import com.wlper.lib.view.adapter.SimpleAdapterWithMarker.OnItemViewClickListener;
import com.wlper.lib.view.loading.BaseLoadLayout;
import com.wlper.lib.view.loading.LoadLayoutWithFrameAnim;
import com.wlper.lib.view.loading.LoadLayoutWithTweenAnim;

/**
 * 首页界面
 * 
 * @author wanliang527
 * 
 */
public class HomeFragment2 extends BaseFragment {
    // private final static String GET_AREA_ERROR = "";

    private final static long GET_NET_DATA_DELAY = 500;

    private final static String DG_ID = "249";
    private final static String DG_AREA_NUM = "0001900017";
    private final static int PAGE_SIZE = 5;
    private ExpandableTab mAreaTab;// 地区筛选栏
    private HorizontalExpandableList mDropAreaView;// 地区筛选栏下拉窗口视图
    private GridView shopType;// 商家类型快捷入口和最新活动视图
    private RadioGroup mRadioGroup;// 切换精选商家和会员日商家
    private NewActysHelper newActysHelper;  //精选商家处理类
//    private GridView newestActivities;// 商家类型快捷入口和最新活动视图
//    private ViewStub newestActivitiesView;// 最新活动
    private ListView mShopList;// 精选商家或者会员日商家列表
    private PullToRefreshScrollView mGlobalView;// 全局滑动View
    private LoadLayoutWithFrameAnim mShopLoadingView;// 精选商家或者会员日商家加载时的背景，包含加载动画和加载失败处理机制

    private GetAreaListRequest mGetAreaListReq;// 获取地区数据的网络请求
    private GetBrandListRequest mGetBrandListReq;// 获取精选商家的网络请求
    private GetDayMerListRequest mGetDayListReq;// 获取特惠日商家的网络请求

    private Button moreButton;// 更多会员日商家按钮
    private Handler mHandler = new Handler();
    private long lastRefreshTime = -1;

    private F_ShopListAdapter fShopAdapter;// 连锁商家适配器
    private int fCounts = -1, fIndex = 0, fPage = 0;// 用于分页加载
    private V_ShopListAdapter vShopAdapter;// 特惠日商家适配器
    private int vCounts = -1, vIndex = 0, vPage = 0;// 用于分页加载

    private GridView mDropGrid;
    private TextView mCityText;
    private LoadLayoutWithTweenAnim mAreaLoadView;

    private AnimationDrawable mTabloidAnim;
    // 点击事件监听器
    private View.OnClickListener clickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            String tag = v.getTag() == null ? "" : (String) v.getTag();
            Intent intent = null;
            if (tag.equals("search")) {
                // 跳转到搜索界面
                intent = new Intent(mActivity, SearchActivity.class);
                startActivityForResult(intent, 1);
                return;
            } else if(tag.equals("tabloid")){
                intent = new Intent(mActivity, TabloidActivity.class);
                mTabloidAnim.stop();
                startActivity(intent);
            }else if (v.getId() == R.id.btn_more_vip_shops) {
                // 跳转到更多特惠日商家
                // intent = new Intent(mActivity, DayShopsActivity.class);
                intent = new Intent(mActivity, AllDayShopsActivity.class);
                startActivity(intent);
                return;
            } else if (v.getId() == R.id.view_change_city) {
                // 跳转到更换城市界面
//                ViewUtils.showToast(mActivity, "change city");
            }
        }

    };

    // 切换精选商家和会员日商家的Tab按钮的状态监听器
    private RadioGroup.OnCheckedChangeListener checkedChangeListener = new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            // 要注意，由于精选商家和会员日商家使用的是同一个商家列表控件
            // 因此，每次切换Tab按钮之前都要清空该界面存在的加载状态提示，例如“加载失败”和“没有数据”
            mShopLoadingView.clear();
            swtichShopList(checkedId);
        }
    };

    // 整个界面上拉下拉事件添加
    private PullToRefreshBase.OnRefreshListener2<ScrollView> pullListener = new PullToRefreshBase.OnRefreshListener2<ScrollView>() {

        @Override
        public void onPullDownToRefresh(
                PullToRefreshBase<ScrollView> refreshView) {
            // ******用户手动更新的话，需要删除缓存 否则得到的很有可能是缓存数据
            if (NetWorkUtils.isNetConnected()) {
                // 删除地区列表的缓存
                CacheConstant.deleteCacheFile(mGetAreaListReq);
                onGetAreaList(DG_ID);
                int id = mRadioGroup.getCheckedRadioButtonId();
                if (id == R.id.ra_btn1) {
                    // 删除精选商家的缓存
                    clearBrandShopList();
                    // 重新获取精选商家
                    onGetBrandShopList();
                } else if (id == R.id.ra_btn2) {
                    clearDayShopList();
                    onGetDayShopList();
                    moreButton.setVisibility(View.GONE);
                }

                mHandler.postDelayed(new Runnable() {

                    @Override
                    public void run() {
                        lastRefreshTime = System.currentTimeMillis();
                        mPreferences
                                .edit()
                                .putLong(Constants.HOME_P_REFRESH_TIME,
                                        lastRefreshTime).commit();
                        mGlobalView.onRefreshComplete();
                        mGlobalView
                                .getLoadingLayoutProxy(true, false)
                                .setLastUpdatedLabel(
                                        TimeUtils
                                                .computeTimeInterval(lastRefreshTime)
                                                + "更新过");
                    }
                }, 2000);
            } else {
                ViewUtils.showToast(mActivity, R.string.cant_connect_network);
                mGlobalView.onRefreshComplete();
            }

        }

        @Override
        public void onPullUpToRefresh(PullToRefreshBase<ScrollView> refreshView) {
            int checkId = mRadioGroup.getCheckedRadioButtonId();
            if (checkId == R.id.ra_btn1) {
                onGetBrandShopList();
            } else if (checkId == R.id.ra_btn2) {
                onGetDayShopList();
            }

        }
    };

    // 商家列表项目事件点击监听
    private OnItemClickListener itemClickListener = new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position,
                long id) {
            int checkedId = mRadioGroup.getCheckedRadioButtonId();
            if (checkedId == R.id.ra_btn1) {
                // *********首页精选商家的点击事件************//
                F_ShopListAdapter.ViewHolder viewHolder = (F_ShopListAdapter.ViewHolder) view
                        .getTag();
                Intent intent = new Intent(getActivity(),
                        ShopListActivity.class);
                intent.putExtra("tag", ShopListActivity.BRAND_LIST);
                intent.putExtra("brandId", viewHolder.brandId);
                intent.putExtra("title", viewHolder.name.getText().toString());
                startActivity(intent);
            } else if (checkedId == R.id.ra_btn2) {
                // **********首页会员日商家的点击事件************//
                V_ShopListAdapter.ViewHolder viewHolder = (V_ShopListAdapter.ViewHolder) view
                        .getTag();
                Intent intent = new Intent(mActivity, ShopDetailActivity.class);
                intent.putExtra("merchant_id", viewHolder.merchantId);
                startActivity(intent);
            }

        }
    };

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        StaticData.AREA_NAME = "全城";
        lastRefreshTime = mPreferences.getLong(Constants.HOME_P_REFRESH_TIME,
                -1);
    }

    // 震动监听器的生命周期是onResume->onPause
    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(this.getClass().getName());
    }

    @Override
    public void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(this.getClass().getName());
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        if (newActysHelper != null) {
            newActysHelper.setTabloidBtnState();
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public View setContentView() {
        View view = mInflater.inflate(R.layout.fragment_home2, null);
        initView(view);
        return view;
    }

    @Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
    }

    /**
     * 初始化标题栏
     */
    @Override
    public boolean initTopBanner() {
        PrintUtils.printo("top bar is re init..");
        defaultInit();
        // ***** 地区筛选栏
        mAreaTab = new ExpandableTab(mActivity);
        mAreaTab.addTabButton("全城");
        mAreaTab.setTitleStyle(R.color.transparent, 15, R.color.white);
        mAreaTab.setTabPadding(10, 0, 10, 0);
        mAreaTab.setRightDrawable(0, R.drawable.selector_expand_tab_title_bg1);
        mAreaTab.setDrawablePadding(0, 20);
        getPartView(LEFT).addView(mAreaTab);
        LinearLayout.LayoutParams tabParams = ((LinearLayout.LayoutParams) mAreaTab
                .getLayoutParams());
        tabParams.gravity = Gravity.CENTER;
        tabParams.height = LinearLayout.LayoutParams.MATCH_PARENT;

        // initDropView_List();
        initDropView_Grid();

        // ***** 小报消息按钮
        ImageButton mTabloidBtn = new ImageButton(mActivity);
        mTabloidBtn.setTag("tabloid");
        mTabloidBtn.setOnClickListener(clickListener);
        mTabloidBtn.setBackgroundResource(R.drawable.drawable_tp2tl_gray);
        mTabloidAnim = (AnimationDrawable) mActivity.getResources().getDrawable(
                R.anim.tabloid_anim);
        mTabloidBtn.setImageDrawable(mTabloidAnim);
        mTabloidAnim.stop();
        getPartView(RIGHT).addView(mTabloidBtn);
        ((LinearLayout.LayoutParams) mTabloidBtn.getLayoutParams()).gravity = Gravity.CENTER;
        
        // ***** 搜索按钮
        ImageButton searchBtn = new ImageButton(mActivity);
        searchBtn.setTag("search");
        searchBtn.setOnClickListener(clickListener);
        searchBtn.setBackgroundResource(R.drawable.drawable_tp2tl_gray);
        searchBtn.setImageResource(R.drawable.selector_search_btn2);
        getPartView(RIGHT).addView(searchBtn);
        ((LinearLayout.LayoutParams) searchBtn.getLayoutParams()).gravity = Gravity.CENTER;
        return true;
    }


    /**
     * 下拉窗口，用网格形式展示地区名
     */
    private void initDropView_Grid() {
        View view = mInflater.inflate(R.layout.view_homefrag_region_selector,
                null);
        mDropGrid = (GridView) view.findViewById(R.id.grid_v);
        mCityText = (TextView) view.findViewById(R.id.txt_v_cur_city);
        mCityText.setText("当前城市：东莞");
        view.findViewById(R.id.view_change_city).setOnClickListener(
                clickListener);
        mAreaLoadView = (LoadLayoutWithTweenAnim) view
                .findViewById(R.id.loading_view);
        mAreaTab.setDropView(0, view, true);
    }

    /**
     * 查找View的Id
     * 
     * @param view
     */
    private void findViewsId(View view) {
        shopType = (GridView) view.findViewById(R.id.grid_v_shop_type);
        mRadioGroup = (RadioGroup) view.findViewById(R.id.ra_group_tabs);
        newActysHelper = new NewActysHelper(mActivity);
        newActysHelper.initNewActysView(view);
        newActysHelper.initTabloidData(mTabloidAnim);
//        newestActivitiesView = (ViewStub) view
//                .findViewById(R.id.view_newest_activities);
//        newestActivities = (GridView) view
//                .findViewById(R.id.grid_v_newest_activities);
        mShopList = (ListView) view.findViewById(R.id.list_v_shops);
        mGlobalView = (PullToRefreshScrollView) view
                .findViewById(R.id.global_view);
        mShopLoadingView = (LoadLayoutWithFrameAnim) view
                .findViewById(R.id.shop_load_view);
        moreButton = (Button) view.findViewById(R.id.btn_more_vip_shops);
    }

    /**
     * 初始化整个界面
     */
    private void initView(final View view) {
        findViewsId(view);
        // 初始化全局的ScrollView
        mGlobalView.setMode(Mode.BOTH);
        mGlobalView.setPullToRefreshOverScrollEnabled(false);
        mGlobalView.getRefreshableView().setVerticalScrollBarEnabled(false);// 隐藏滚动条

        Screen screen = Screen.getInstance(mActivity);
        mGlobalView.setMinimumHeight(screen.getScreenHeight());
        mGlobalView.setOnRefreshListener(pullListener);
        final Drawable headDrawable = getResources().getDrawable(
                R.drawable.wl_anim_header_loading);

        mGlobalView
                .setOnPullEventListener(new PullToRefreshBase.OnPullEventListener<ScrollView>() {

                    @Override
                    public void onPullEvent(
                            PullToRefreshBase<ScrollView> refreshView,
                            State state, Mode direction) {
                        if (State.PULL_TO_REFRESH == state) {
                            ((AnimationDrawable) headDrawable).start();
                            if (lastRefreshTime != -1) {
                                mGlobalView
                                        .getLoadingLayoutProxy(true, false)
                                        .setLastUpdatedLabel(
                                                TimeUtils
                                                        .computeTimeInterval(lastRefreshTime)
                                                        + "更新过");
                            }
                        } else if (State.RESET == state) {
                            ((AnimationDrawable) headDrawable).stop();
                        }

                    }
                });
        // 获取头部下拉区域
        ILoadingLayout headerLayout = mGlobalView.getLoadingLayoutProxy(true,
                false);
        headerLayout.setTextTypeface(Typeface.SERIF);
        headerLayout.setLoadingDrawable(headDrawable);
        headerLayout.setPullLabel(getResources().getString(
                R.string.xlistview_header_hint_normal));
        headerLayout.setReleaseLabel(getResources().getString(
                R.string.xlistview_header_hint_ready));
        headerLayout.setRefreshingLabel(getResources().getString(
                R.string.xlistview_header_hint_refresh));
        if (lastRefreshTime != -1) {
            headerLayout.setLastUpdatedLabel(TimeUtils
                    .computeTimeInterval(lastRefreshTime) + "更新过");
        }
        FrameLayout hInnerLayout = mGlobalView.getHeaderLayout()
                .getInnerLayout();
        int left = hInnerLayout.getPaddingLeft();
        int right = hInnerLayout.getPaddingRight();
        int top = hInnerLayout.getPaddingTop();
        hInnerLayout.setPadding(left, top, right, 0);

        ILoadingLayout footerLayout = mGlobalView.getLoadingLayoutProxy(false,
                true);
        footerLayout.setLoadingDrawable(getResources().getDrawable(
                R.drawable.wl_ic_loading));
        footerLayout.setPullLabel(getResources().getString(
                R.string.xlistview_footer_hint_normal));
        footerLayout.setReleaseLabel(getResources().getString(
                R.string.xlistview_header_hint_ready));
        footerLayout.setRefreshingLabel(getResources().getString(
                R.string.xlistview_footer_hint_loading));
        footerLayout.setTextTypeface(Typeface.SERIF);

        // 初始化商家类型选择
        shopType.setAdapter(new SimpleAdapter(mActivity, StaticData
                .getHomeShopTypes(), R.layout.shop_type_grid_v_item,
                new String[] { "name", "icon" }, new int[] {
                        R.id.txt_v_shop_type, R.id.image_v_shop_type_icon }));
        shopType.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // **********商家类型的点击事件监听***********//
                TextView txtView = (TextView) view
                        .findViewById(R.id.txt_v_shop_type);
                StaticData.INDUSTRY_NAME = txtView.getText().toString().trim();
                MainTabActivity.mTabHost.setCurrentTab(1);
            }
        });
//        // 初始化最新活动
//        newActysHelper.showNewestActyView(view);
        // 初始化精选商家和会员日商家切换按钮
        mRadioGroup.setOnCheckedChangeListener(checkedChangeListener);
        // 初始化商家列表
        mShopList.setOnItemClickListener(itemClickListener);
        mShopLoadingView.setStateHandler(loadStateHandler);
        // onGetAreaList(DG_ID);
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                onGetAreaList(DG_ID);
                onGetBrandShopList();
            }
        }, GET_NET_DATA_DELAY);
        // 更多会员日商家按钮点击事件添加
        moreButton.setOnClickListener(clickListener);
    }


    /**
     * 获取地区数据
     * 
     */
    private void onGetAreaList(String parentId) {
        if (mAreaLoadView != null) {
            mAreaLoadView.onLoading();
        }
        if (mGetAreaListReq == null) {
            mGetAreaListReq = new GetAreaListRequest(parentId);
            mGetAreaListReq
                    .setActionListener(new ActionListener<GetAreaListResponse>() {
                        @Override
                        public void onSuccess(GetAreaListResponse result) {
                            LogUtils.logNetReturn(Constants.getAreaList,
                                    result.responseStr);
                            if (result.statusStr.equals("SUCCESS")) {
                                if (mDropGrid!=null) {
                                    updateAreaGridView(result);
                                }else {
                                    updateAreaListView(result);
                                }
                            } else {
                                LogUtils.logNetError("获取地区数据失败---"
                                        + result.statusStr);
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);
                            }
                        }

                        @Override
                        public void onFailure(int resultCode) {
                            LogUtils.logNetError("获取地区数据失败---" + resultCode
                                    + "");
                            if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                                ViewUtils.showToast(mActivity,
                                        R.string.cant_connect_network);
                            } else {
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);
                            }

                        }
                    });
        } else {
            mGetAreaListReq.getParams().clear();
            mGetAreaListReq.getParams().put(GetAreaListRequest.PARENT_ID,
                    parentId);
            mGetAreaListReq.getParams().put(GetAreaListRequest.CHSH_TOKEN,
                    Constants.TOKEN);
            mGetAreaListReq.encryption();
        }
        NetCacheClient.httpCacheGet(mGetAreaListReq);

    }

    /**
     * 更新地区筛选下拉窗口视图
     * 
     * @param result
     */
    private void updateAreaListView(GetAreaListResponse result) {
        if (mDropAreaView != null) {
            List<Area> areaList = result.areas;
            ArrayList<String> areaStrList = new ArrayList<String>();
            areaStrList.add("全城");
            for (int i = 0; i < areaList.size(); i++) {
                Area area = areaList.get(i);
                areaStrList.add(area.name);
            }
            HorizontalExpandableList.ExpandableListAdapter adapter = mDropAreaView
                    .getAdapter();
            if (adapter == null) {
                adapter = new HorizontalExpandableList.ExpandableListAdapter(
                        areaStrList, new SparseArray<List<String>>());
            } else {
                adapter.clearAll();
                adapter.addAll(areaStrList, new SparseArray<List<String>>());
            }
            mDropAreaView.setAdapter(adapter);
        }

    }

    private void updateAreaGridView(GetAreaListResponse result) {
        if (mDropGrid != null) {
            List<Area> areaList = result.areas;
            List<Map<String, Object>> areaStrList = new ArrayList<Map<String, Object>>();
            Map<String, Object> m = new HashMap<String, Object>();
            m.put("region", "全城");
            areaStrList.add(m);
            for (int i = 0; i < areaList.size(); i++) {
                Area area = areaList.get(i);
                Map<String, Object> map = new HashMap<String, Object>();
                map.put("region", area.name);
                areaStrList.add(map);
            }
            SimpleAdapterWithMarker adapter = (SimpleAdapterWithMarker) mDropGrid
                    .getAdapter();
            // if (adapter == null) {
            adapter = new SimpleAdapterWithMarker(mActivity, areaStrList,
                    R.layout.view_grid_v_item, new String[] { "region" },
                    new int[] { R.id.txt_v_grid_item });
            adapter.setItemBackground(R.color.ex_list_normal,
                    R.color.ex_list_selected);
            adapter.setItemClickListener(new OnItemViewClickListener() {

                @Override
                public void onItemClick(View itemView, int itemViewPos) {
                    String itemName = ((TextView) itemView).getText()
                            .toString();
                    StaticData.AREA_NAME = itemName;
                    refreshTabButton(0, itemName);

                }
            });
            // } else {
            // adapter.getData().clear();
            // adapter.getData().addAll(areaStrList);
            // }

            mDropGrid.setAdapter(adapter);
        }
    }

    /**
     * 刷新Tab按钮
     * 
     * @param showText
     */
    private void refreshTabButton(int pos, String showText) {
        if (mAreaTab != null)
            mAreaTab.onRefresh(pos, showText);
    }

    /**
     * 切换商家列表
     * 
     * @param checkId
     */
    private void swtichShopList(int checkId) {
        if (checkId == R.id.ra_btn1) {
            // 隐藏更多会特惠日商家按钮
            moreButton.setVisibility(View.GONE);
            if (fShopAdapter == null) {
                // 适配器如果为空，说明是第一次获取数据
                mShopList.setAdapter(null);
                onGetBrandShopList();
            } else {
                mGlobalView.onRefreshComplete();
                mShopList.setAdapter(fShopAdapter);
            }
        } else if (checkId == R.id.ra_btn2) {
            // 根据情况显示更多特惠日商家按钮
            if (vShopAdapter == null) {
                mShopList.setAdapter(null);
                onGetDayShopList();
            } else {
                showMoreButtonDepends();
                mGlobalView.onRefreshComplete();
                mShopList.setAdapter(vShopAdapter);
            }
        }
    }

    /**
     * 获取连锁商家列表
     * 
     * @return 是否成功调用网络连接
     */
    private boolean onGetBrandShopList() {
        final boolean isFirst = fCounts < 0 ? true : false;
        if (isFirst)
            mShopLoadingView.onLoading();
        // 如果连锁商家的数量大于等于0，说明已经从服务器获得过真实的商家数量
        // 如果索引值大于等于数量，说明服务器的数据已经都取完了，无需再联网
        if (fCounts >= 0 && fIndex >= fCounts) {
            mShopLoadingView.clear();
            ViewUtils.showToast(mActivity, R.string.no_data_anymore);
            mGlobalView.onRefreshComplete();
            return false;
        }
        if (mGetBrandListReq == null) {
            mGetBrandListReq = new GetBrandListRequest(DG_AREA_NUM);
            mGetBrandListReq
                    .setActionListener(new ActionListener<GetBrandListResponse>() {
                        @Override
                        public void onSuccess(GetBrandListResponse result) {
                            mGlobalView.onRefreshComplete();
                            LogUtils.logNetReturn(Constants.getBrandList,
                                    result.responseStr);
                            if (result.statusStr.equals("SUCCESS")) {
                                // 商家数量经过第一次获取后就固定不变了
                                if (isFirst)
                                    fCounts = Integer.valueOf(result.total);
                                int size = result.brandList.size();
                                // 此时要判断数据是否为空，由于前面已经加了判断，故只有两种情况可能得到商家数量为0
                                // 第一种情况是首次加载的时候，第二种情况是接口出现问题
                                // 首次加载数据为空的话，要显示没有数据的提示界面；如果接口返回商家数量为0，则保持原有列表不变，提示“没有更多了”
                                // 否则才更新商家列表
                                if (size == 0) {
                                    if (isFirst)
                                        mShopLoadingView.onNoData();
                                    ViewUtils.showToast(mActivity,
                                            R.string.no_data_anymore);
                                } else {
                                    mShopLoadingView.onLoadSuccess();
                                    updateFshopList(result);
                                }

                            } else {
                                fPage--;
                                LogUtils.logNetError("获取精选商家失败---"
                                        + result.statusStr);
                                if (isFirst)
                                    mShopLoadingView.onLoadFailed();
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);

                            }
                        }

                        @Override
                        public void onFailure(int resultCode) {
                            mGlobalView.onRefreshComplete();
                            fPage--;
                            LogUtils.logNetError("获取精选商家失败---" + resultCode);
                            if (isFirst)
                                mShopLoadingView.onLoadFailed();
                            if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                                ViewUtils.showToast(mActivity,
                                        R.string.cant_connect_network);
                            } else {
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);
                            }

                        }

                    });
        }
        mGetBrandListReq.getParams().clear();
        mGetBrandListReq.add(GetBrandListRequest.AREA_NUM, DG_AREA_NUM);
        mGetBrandListReq.add(GetBrandListRequest.TOKEN, Constants.TOKEN);
        mGetBrandListReq.add(GetBrandListRequest.PAGE_NUM, (++fPage) + "");
        mGetBrandListReq.add(GetBrandListRequest.PAGE_SIZE, PAGE_SIZE + "");
        mGetBrandListReq.encryption();
        NetCacheClient.httpCacheGet(mGetBrandListReq);
        return true;
    }

    /**
     * 更新连锁商家列表
     * 
     * @param result
     */
    private void updateFshopList(GetBrandListResponse result) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        int retCounts = result.brandList.size();
        fIndex = fIndex + retCounts;
        for (int i = 0; i < retCounts; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coverUrl", result.brandList.get(i).midPhotoUrl);
            map.put("name", result.brandList.get(i).name);
            map.put("description", result.brandList.get(i).describe);
            map.put("brandId", result.brandList.get(i).brandId);
            data.add(map);
        }
        if (fShopAdapter == null) {
            fShopAdapter = new F_ShopListAdapter(mActivity, data);
            mShopList.setAdapter(fShopAdapter);
        } else {
            fShopAdapter.getData().addAll(data);
            fShopAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 清空连锁商家数据，包括缓存和内存。
     */
    private void clearBrandShopList() {
        CacheConstant.deleteCacheFolder(Constants.getBrandList);
        fCounts = -1;
        fIndex = 0;
        fPage = 0;
        if (fShopAdapter != null)
            fShopAdapter.getData().clear();
    }

    /**
     * 获取特惠日商家
     * 
     * @return 是否成功调用网络数据
     */
    private boolean onGetDayShopList() {
        final boolean isFirst = vCounts < 0 ? true : false;
        if (isFirst)
            mShopLoadingView.onLoading();
        // 如果特惠日商家的数量大于等于0，说明已经从服务器获得过真实的商家数量
        // 如果索引值大于等于数量，说明服务器的数据已经都取完了，无需再联网
        if (vCounts >= 0 && vIndex >= vCounts) {
            mShopLoadingView.clear();
            ViewUtils.showToast(mActivity, R.string.no_data_anymore);
            mGlobalView.onRefreshComplete();
            showMoreButtonDepends();
            return false;
        }
        if (mGetDayListReq == null) {
            mGetDayListReq = new GetDayMerListRequest().add(
                    GetDayMerListRequest.AREA_NUM, DG_AREA_NUM);
            
            mGetDayListReq
                    .setActionListener(new ActionListener<GetDayMerListResponse>() {
                        @Override
                        public void onSuccess(GetDayMerListResponse result) {
                            mGlobalView.onRefreshComplete();
                            LogUtils.logNetReturn(Constants.getDayMerList,
                                    result.responseStr);
                            if (result.statusStr.equals("SUCCESS")) {
                                // 商家数量经过第一次获取后就固定不变了
                                if (isFirst)
                                    vCounts = Integer.valueOf(result.total);
                                int size = result.dayMerList.size();
                                // 此时要判断数据是否为空，由于前面已经加了判断，故只有两种情况可能得到商家数量为0
                                // 第一种情况是首次加载的时候，第二种情况是接口出现问题
                                // 首次加载数据为空的话，要显示没有数据的提示界面；如果接口返回商家数量为0，则保持原有列表不变，提示“没有更多了”
                                // 否则才更新商家列表
                                if (size == 0) {
                                    if (isFirst)
                                        mShopLoadingView.onNoData();
                                    ViewUtils.showToast(mActivity,
                                            R.string.no_data_anymore);
                                } else {
                                    mShopLoadingView.onLoadSuccess();
                                    updateVshopList(result);
                                }

                            } else {
                                vPage--;
                                LogUtils.logNetError("获取特惠日商家失败---"
                                        + result.statusStr);
                                if (isFirst)
                                    mShopLoadingView.onLoadFailed();
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);
                            }
                        }

                        @Override
                        public void onFailure(int resultCode) {
                            mGlobalView.onRefreshComplete();
                            vPage--;
                            LogUtils.logNetError("获取特惠日商家失败---" + resultCode);
                            if (isFirst)
                                mShopLoadingView.onLoadFailed();
                            if (resultCode == NetClient.NET_DISCONNECT_CODE) {
                                ViewUtils.showToast(mActivity,
                                        R.string.cant_connect_network);
                            } else {
                                ViewUtils.showToast(mActivity,
                                        R.string.network_error);
                            }
                        }
                    });
        }
        int week = Calendar.getInstance(TimeZone.getTimeZone("GMT+8:00")).get(
                Calendar.DAY_OF_WEEK) - 1;
        mGetDayListReq.getParams().clear();
        mGetDayListReq.add(GetDayMerListRequest.AREA_NUM, DG_AREA_NUM);
        mGetDayListReq.add(GetDayMerListRequest.TOKEN, Constants.TOKEN);
        mGetDayListReq.add(GetDayMerListRequest.PAGE_NUM, ++vPage + "");
        mGetDayListReq.add(GetDayMerListRequest.PAGE_SIZE, PAGE_SIZE + "");
        mGetDayListReq.add(GetDayMerListRequest.WEEK, week + "");
        mGetDayListReq.encryption();
        NetCacheClient.httpCacheGet(mGetDayListReq);
        return true;
    }

    /**
     * 更新特惠日商家列表
     * 
     * @param result
     */
    private void updateVshopList(GetDayMerListResponse result) {
        List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
        int retCounts = result.dayMerList.size();
        vIndex = vIndex + retCounts;
        showMoreButtonDepends();
        for (int i = 0; i < retCounts; i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("coverUrl", result.dayMerList.get(i).midPhotoUrl);
            map.put("name", result.dayMerList.get(i).merchantName);
            map.put("disContent", result.dayMerList.get(i).preferential);
            map.put("discount",
                    getDiscountType(result.dayMerList.get(i).preferentialType));
            map.put("merchantId", result.dayMerList.get(i).merchantId);
            data.add(map);
        }
        if (vShopAdapter == null) {
            vShopAdapter = new V_ShopListAdapter(mActivity, data);
            mShopList.setAdapter(vShopAdapter);
        } else {
            vShopAdapter.getData().addAll(data);
            vShopAdapter.notifyDataSetChanged();
        }
    }

    /**
     * 清空特惠日商家数据，包括缓存和内存
     */
    private void clearDayShopList() {
        CacheConstant.deleteCacheFolder(Constants.getDayMerList);
        vCounts = -1;
        vIndex = 0;
        vPage = 0;
        if (vShopAdapter != null)
            vShopAdapter.getData().clear();
    }

    /**
     * 显示其它特惠日商家按钮
     */
    private void showMoreButtonDepends() {
        if (vCounts >= 0 && vIndex >= vCounts
                && moreButton.getVisibility() != View.VISIBLE)
            moreButton.setVisibility(View.VISIBLE);
    }

    /**
     * 根据优惠类型代号返回优惠类型描述
     * 
     * @param code
     * @return
     */
    public static String getDiscountType(String code) {
        if (code.equals("0")) {
            return "免费";
        } else if (code.equals("1")) {
            return "赠送";
        } else {
            return "打折";
        }
    }

    /**
     * 隐藏下拉窗口
     * 
     * @return 隐藏成功的话返回true，否则返回false
     */
    public boolean hideDropWindow() {
        if (mAreaTab != null)
            return mAreaTab.hideDropdownWindow();
        return false;
    }

    /**
     * 商家列表加载状态的处理
     */
    private BaseLoadLayout.LoadStateHandler loadStateHandler = new BaseLoadLayout.LoadStateHandler() {

        @Override
        public void onReload() {
            int checkedId = mRadioGroup.getCheckedRadioButtonId();
            if (checkedId == R.id.ra_btn1) {
                onGetBrandShopList();
            } else if (checkedId == R.id.ra_btn2) {
                onGetDayShopList();
            }
        }

        @Override
        public void onLoading() {
        }

        @Override
        public void onLoadSuccess() {
        }

        @Override
        public void onLoadFailed() {
        }
    };
}
